package com.bigknow.appstore.proxy.server;

import com.bigknow.appstore.proxy.entity.ProxyMeta;
import com.bigknow.appstore.proxy.service.ProxyManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * Created by chaos on 2016/10/31.
 */
@Service
public class Shutdown {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ProxyManager proxyManager;

    @PostConstruct
    public void shutdown(){

        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                if(proxyManager!=null){
                    logger.info("shut down http proxy server");
                    List<ProxyMeta> list =  proxyManager.findAllProxyMeta();
                    for (ProxyMeta proxyMeta : list) {
                        logger.info("stop ProxyServer id is :"+ proxyMeta.getId());
                        proxyManager.stopProxyServer(proxyMeta.getId());
                    }
                }
            }
        });
    }

}
